import React, {
    PureComponent
} from 'react';

import {
    View,
    InteractionManager
} from 'react-native';

interface Props {
    onCreated: Function
}

interface State {
    Node: any
}

interface Ref {
    onPageEnter?: Function,
    onPageLeave?:Function
}

export default (load: Function) => (
    class LazyLoad extends PureComponent<Props, State> {
        state = {
            Node: View
        }

        private Ref: any = null;

        UNSAFE_componentWillMount() {
            this.loadNode();
        }

        private loadNode = async () => {
            const node = await load()

            const _state: State = {
                Node: node.default
            }

            this.setState(
                _state,
                this.onCreated
            )
        }

        //异步创建
        private onCreated = () => {
            const {
                onCreated
            } = this.props as Props;
            onCreated(this.onEnterHook)
        }

        private onEnterHook = () => {
            InteractionManager.runAfterInteractions(
                this.onPageEnter
            )
        }

        private onPageEnter = () => {
            const page = this.Ref as Ref;
            if (page && !!page.onPageEnter) {
                page.onPageEnter()
            }
        }

        render() {
            const {
                Node
            } = this.state;

            return (
                <Node
                    {...this.props}
                    ref={e => this.Ref = e}
                />
            )
        }
    }
)